<template>
  <div class="page">
    <SearchToolbar
      v-if="showToolbar"
      :categories="categories"
      :tags="tags"
      :category-id="categoryId"
      :tag-id="tagId"
      :keyword="keyword"
      :sort-by="sortBy"
      :sort-options="sortOptions"
      @update:categoryId="v => { categoryId = v as any }"
      @update:tagId="v => { tagId = v as any }"
      @update:keyword="v => { keyword = v || '' }"
      @update:sortBy="v => { sortBy = v }"
      @change="onFilterChange"
      @search="onSearch"
    />

    <HotSection v-if="showHot" :category-id="props.hotCategoryId" :tag-id="props.hotTagId" :default-since-days="hotSinceDays" />
    <div class="more" v-if="showHot"><a @click="$router.push({ name: 'HotPage' })">更多 &gt;</a></div>
    
    <RecentSection v-if="showRecent" :limit="8" />

    <SkeletonList v-if="loading" :count="6" />
    <EmptyState v-else-if="!loading && (!list || list.length === 0)" text="暂无文章" />
    <a-list v-else
      :grid="{ gutter: 16, xs: 1, sm: 2, md: 2, lg: 3, xl: 4, xxl: 4 }"
      :data-source="list"
      :pagination="false"
    >
      <template #renderItem="{ item }">
        <a-list-item>
          <ArticleCard :item="item" @click="(id) => goDetail(id)" @click-category="goCategory" />
        </a-list-item>
      </template>
    </a-list>

    <Pager :page-no="pageNo" :page-size="pageSize" :total="total" @update:pageNo="onPageChange" @update:pageSize="(_, s) => onSizeChange(0, s)" />
  </div>
  
</template>

<script setup lang="ts">
import { ref, onMounted, watch } from 'vue'
import { usePageQuery } from '@/composables/usePageQuery'
import { fetchArticles, fetchCategories, fetchTags, fetchHotArticles, fetchRecentArticles } from '@/api/public/articles'
import type { ArticleListItemVO, CategoryVO, TagVO } from '@/types/api'
import { useRouter, useRoute } from 'vue-router'
import dayjs from 'dayjs'
import ArticleCard from '@/components/ArticleCard.vue'
import SearchToolbar from '@/components/SearchToolbar.vue'
import Pager from '@/components/Pager.vue'
import HotSection from '@/components/HotSection.vue'
import RecentSection from '@/components/RecentSection.vue'
import EmptyState from '@/components/EmptyState.vue'
import SkeletonList from '@/components/SkeletonList.vue'

const router = useRouter()
const route = useRoute()

const props = defineProps<{
  categoryId?: number
  tagId?: number
  keywordProp?: string
  showToolbar?: boolean
  showHot?: boolean
  showRecent?: boolean
  hotCategoryId?: number
  hotTagId?: number
  hotSinceDays?: number
}>()

const loading = ref(false)
const list = ref<ArticleListItemVO[]>([])
const hotList = ref<ArticleListItemVO[]>([])
const recentList = ref<ArticleListItemVO[]>([])
const total = ref(0)
const { pageNo, pageSize, categoryId, tagId, keyword, sortBy, pushQuery } = usePageQuery({ pageNo: 1, pageSize: 12, sortBy: 'latest' })
const sortOptions = [
  { label: '最新', value: 'latest' },
  { label: '最热', value: 'views' },
  { label: '点赞', value: 'likes' },
  { label: '评论', value: 'comments' }
]
const categories = ref<CategoryVO[]>([])
const tags = ref<TagVO[]>([])
const fallbackCover = 'https://via.placeholder.com/400x240?text=No+Cover'
const showToolbar = ref(props.showToolbar !== false)
const showHot = ref(props.showHot !== false)
const showRecent = ref(props.showRecent !== false)
const hotSinceDays = ref<number>(props.hotSinceDays ?? 30)
const hotWindowOptions = [
  { label: '7天', value: 7 },
  { label: '30天', value: 30 },
  { label: '全部', value: 0 }
]

async function load() {
  loading.value = true
  try {
    const { data } = await fetchArticles({
      keyword: keyword.value || undefined,
      categoryId: categoryId.value,
      tagId: tagId.value,
      pageNo: pageNo.value,
      pageSize: pageSize.value,
      status: 1,
      sortBy: sortBy.value
    })
    list.value = data.records
    total.value = data.total
  } finally {
    loading.value = false
  }
}

async function loadHot() {
  const since = hotSinceDays.value && hotSinceDays.value > 0 ? hotSinceDays.value : undefined
  const { data } = await fetchHotArticles(8, props.hotCategoryId, props.hotTagId, since)
  hotList.value = data || []
}

async function loadRecent() {
  const { data } = await fetchRecentArticles(8)
  recentList.value = data || []
}

function onPageChange(p: number) { pageNo.value = p; pushQuery(); load() }

function onSizeChange(_: number, size: number) { pageSize.value = size; pageNo.value = 1; pushQuery(); load() }

function onSearch() { pageNo.value = 1; pushQuery(); load() }

function onFilterChange() { pageNo.value = 1; pushQuery(); load() }

function onSortChange() { pageNo.value = 1; pushQuery(); load() }

function goDetail(id: number) {
  router.push({ name: 'ArticleDetail', params: { id: String(id) } })
}

function goCategory(item: ArticleListItemVO) {
  if (item.categoryId) {
    console.log(item)
    router.push({ name: 'CategoryPage', params: { id: String(item.categoryId) } })
  } else if (item.categoryName) {
    keyword.value = item.categoryName
    pageNo.value = 1
    load()
  }
}

function parseTagNames(s?: string): string[] {
  if (!s) return []
  return s.split(',').map(v => v.trim()).filter(Boolean)
}

function goTagByName(name: string) {
  const found = tags.value.find(t => t.name === name)
  if (found) {
    tagId.value = tagId.value === found.id ? undefined : found.id
    pageNo.value = 1
    load()
    return
  }
  keyword.value = name
  pageNo.value = 1
  load()
}

function formatTime(s: string) {
  return dayjs(s).format('YYYY-MM-DD HH:mm:ss')
}

onMounted(async () => {
  // 从 URL 读取查询参数
  // 初始参数已由 usePageQuery 从路由恢复

  // 初始化 props 到内部状态
  if (props.keywordProp != null) keyword.value = props.keywordProp || ''
  if (props.categoryId != null) categoryId.value = props.categoryId
  if (props.tagId != null) tagId.value = props.tagId

  const [c, t] = await Promise.all([fetchCategories(), fetchTags()])
  categories.value = c.data || []
  tags.value = t.data || []
  const tasks: Promise<any>[] = [load()]
  if (showHot.value) tasks.push(loadHot())
  if (showRecent.value) tasks.push(loadRecent())
  await Promise.all(tasks)
})

// 监听外部 props 变化，联动刷新
watch(() => [props.keywordProp, props.categoryId, props.tagId], ([k, c, t]) => {
  keyword.value = typeof k === 'string' ? k : ''
  categoryId.value = typeof c === 'number' ? c : undefined
  tagId.value = typeof t === 'number' ? t : undefined
  pageNo.value = 1
  load()
})

// 使用 usePageQuery 提供的 pushQuery

function onHotWindowChange() {
  loadHot()
}
</script>

<style scoped>
.page {
  max-width: 1200px;
  margin: 0 auto;
  padding: 12px;
}
.toolbar {
  margin-bottom: 12px;
}
.article-card {
  height: 100%;
}
.summary {
  color: rgba(0,0,0,0.65);
  margin-top: 8px;
  display: -webkit-box;
  -webkit-line-clamp: 3;
  line-clamp: 3;
  -webkit-box-orient: vertical;
  overflow: hidden;
}
.meta {
  margin-top: 8px;
  display: flex;
  gap: 12px;
  color: rgba(0,0,0,0.45);
  font-size: 12px;
}
.meta .link { cursor: pointer; color: #1677ff; }
.meta .link:hover { text-decoration: underline; }
.stats {
  margin-top: 8px;
  display: flex;
  gap: 12px;
  color: rgba(0,0,0,0.45);
  font-size: 12px;
}
.tags {
  margin-top: 8px;
}
.more { text-align: right; margin-top: 8px; }
.pager {
  margin-top: 16px;
  text-align: center;
}
</style>


